//
//  ARTScanDeviceController.m
//  ChartsDemo
//
//  Created by wusiping on 2021/3/28.
//

#import "ARTScanDeviceController.h"
// controllers
#import "ARTMainTabController.h"
#import "HelpViewController.h"
// views
#import "XLKWavePulsLayer.h"
#import "TopImageTwoBottomLabelCell.h"
// models
#import "BabyBluetooth.h"
#import "ARTVersionUpdateHelper.h"

@interface ARTScanDeviceController ()<UICollectionViewDelegate,UICollectionViewDataSource,CBPeripheralDelegate>{
    // 搜索秒数
    NSInteger _searchTimeCount;
    // 等待秒数
    NSInteger _waitTimeCount;
    // 连接秒数
    NSInteger _connectTimeCount;
    BOOL _isBegainConnect;
}

@property (nonatomic,strong) BabyBluetooth *baby;
@property (nonatomic,strong) CBPeripheral *currentPeripheral;
@property (nonatomic,strong) CBCharacteristic *currentCharacteristic;

@property (nonatomic,strong) XLKWavePulsLayer *waveLayer;
@property (nonatomic,strong) UIButton *historyBtn;
@property (nonatomic,strong) UIView *bgView;
@property (nonatomic,strong) UILabel *searchStatusLabel;
@property (nonatomic,strong) UIButton *questionBtn;
@property (nonatomic,strong) UILabel *promptLabel;
@property (nonatomic,strong) UIView *unFindBg;
@property (nonatomic,strong) UIButton *reSearchBtn;
@property (nonatomic,strong) UIImageView *searchImg;
@property (nonatomic,strong) UICollectionView *baseCollectionView;
@property (nonatomic,strong) UILabel *reSearchLabel;
@property (nonatomic,strong) UILabel *noBluetoothLabel;

@property (nonatomic,strong) NSTimer *searchTimer; // 搜索定时器
@property (nonatomic,strong) NSTimer *waitTimer;// 等待定时器
@property (nonatomic,strong) NSTimer *connectTimer;// 连接定时器

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (strong, nonatomic)  NSMutableDictionary *macAddressDictionary;

@property (strong, nonatomic)  UIAlertController *alertController;

@end

@implementation ARTScanDeviceController

const float circleRadius = 150;
- (void)initAlertController{
    _alertController = [UIAlertController alertControllerWithTitle:FYLocalizedString(@"watch_alert", @"") message:FYLocalizedString(@"watch_alert_set", @"") preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:FYLocalizedString(@"watch_setting",@"") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        UIApplication *application = [UIApplication sharedApplication];
        NSURL *URL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [application openURL:URL options:@{}
               completionHandler:^(BOOL success) {
            }];
        } else {
            [application openURL:URL options:[NSDictionary new] completionHandler:nil];
        }
    }];
    UIAlertAction *setAction = [UIAlertAction actionWithTitle:FYLocalizedString(@"watch_close", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [_alertController addAction:cancelAction];
    [_alertController addAction:setAction];
}
#pragma mark--THE LIFE CYCLE
- (void)viewDidLoad {
    [super viewDidLoad];
    [self UIConfig];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startAnimation) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshLanguage) name:ART_Notify_LanguageChanged object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disConnected) name:ART_Storage_ConnectStatus object:nil];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [ARTVersionUpdateHelper detectionVersion];
//    });
}

- (void)dealloc{
    J_Remove_Notify(self);
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self clearData];
    [self stopBluetooth];
    [self showAlertView];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.waveLayer start];
    [self startSearch];
    ARTSingleShare.hadLoadTabVC = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self destroySearchTimer];
    [self destroyWaitTimer];
}

- (void)initBluetooth{
    NSLog(@"初始化蓝牙");
    [self clearData];
    // 初始化BabyBluetooth蓝牙库
    self.baby = [BabyBluetooth shareBabyBluetooth];
    // 单利存储当前蓝牙
    ARTSingleShare.baby = self.baby;
    NSLog(@"当前连接的设备=%@",[_baby findConnectedPeripherals]);
    [self.baby cancelAllPeripheralsConnection];
    NSLog(@"当前连接的设备2=%@",[_baby findConnectedPeripherals]);
    // 设置蓝牙委托
    [self babyDelegate];
    // 设置委托后直接可以使用，无需等待CBCentralManagerStatePoweredOn状态
    self.baby.scanForPeripherals().begin();
    
    [self destroyWaitTimer];
    [self destroySearchTimer];
    _searchTimeCount = 0;
    self.searchTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(searchTimeAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.searchTimer forMode:NSRunLoopCommonModes];
}

- (void)showAlertView{
    if (ARTSingleShare.currentBluetoothOpen) {
        [self.alertController dismissViewControllerAnimated:YES completion:nil];
        self.alertController = nil;
    }else{
        if ([self isCurrentPage]) {
            [self initAlertController];
            [self presentViewController:self.alertController animated:YES completion:nil];
        }
    }
    self.noBluetoothLabel.hidden = (ARTSingleShare.currentBluetoothOpen);
}

// 设置委托
- (void)babyDelegate{
    WEAK_SELF;
    // 设置蓝牙状态变化委托
    [self.baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        STRONG_SELF;
        NSLog(@"====状态变化了:%@",central);
        self.noBluetoothLabel.hidden = (central.state == CBManagerStatePoweredOn);
        if (central.state == CBManagerStatePoweredOn) {
            ARTSingleShare.currentBluetoothOpen = YES;
        }else{
            ARTSingleShare.currentBluetoothOpen = NO;
        }
        [self showAlertView];
    }];
    
    // 设置查找设备的过滤器
    [self.baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        // 最常用的场景是查找某一个前缀开头的设备
//        if ([peripheralName hasPrefix:@"T"] ) {
            return YES;
//    }
    }];
    
    // 设置扫描到设备的委托
    [self.baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        STRONG_SELF;
        if (![self isCurrentPage]) {
            return;
        }
        if ([Tool deviceTypeWithName:peripheral.name] == ARTDeviceTypeOximeter || [Tool deviceTypeWithName:peripheral.name] == ARTDeviceTypePlateau) {
            NSLog(@"====查找到的oximeter设备:%@",peripheral.name);

            [[NSNotificationCenter defaultCenter] postNotificationName:ART_Notify_FindBlood object:@{@"peripheral":peripheral}];
            [self destroySearchTimer];
            [self addDevice:peripheral advertisement:advertisementData];
        }else if ([Tool deviceTypeWithName:peripheral.name] == ARTDeviceTypeFetalHeart){
            NSLog(@"====查找到的fetalHeart设备:%@",peripheral.name);
            
            [self destroySearchTimer];
            [self addDevice:peripheral advertisement:advertisementData];
        }else if ([Tool deviceTypeWithName:peripheral.name] == ARTDeviceTypeWatch){
            NSLog(@"====查找到的手表设备:%@",peripheral.name);
            [self destroySearchTimer];
            [self addDevice:peripheral advertisement:advertisementData];
        }else if ([Tool deviceTypeWithName:peripheral.name] == ARTDeviceTypePelvicMuscles){
            NSLog(@"====查找到的设备:%@",peripheral.name);
            [self destroySearchTimer];
            [self addDevice:peripheral advertisement:advertisementData];
        }
    }];
    
    // 设置设备连接成功委托
    [self.baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
        STRONG_SELF;
        if ([Tool deviceTypeWithName:peripheral.name] == ARTDeviceTypePelvicMuscles){
            [Tool startingVoiceBroadcastWithAudioName:@"lanyalianjiechenggong"];
        }
        if (![self isCurrentPage]) {
            return;
        }
        if (self->_isBegainConnect) {
            NSLog(@"====连接成功设备name：%@",peripheral.name);
            // 连接成功后，停止扫描
            [self.baby cancelScan];
        }else{
            [self.baby cancelPeripheralConnection:peripheral];
        }
        self->_isBegainConnect = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:ART_Notify_PelvicFloorTrainingBluetoothConnection object:nil];
    }];
    
    // 设置设备连接失败委托
    [self.baby setBlockOnFailToConnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        STRONG_SELF;
        if (![self isCurrentPage]) {
            return;
        }
        NSLog(@"====连接失败设备name：%@",peripheral.name);
        self->_isBegainConnect = NO;
        self.baby.scanForPeripherals().begin();
    }];
        
    // 设置设备断开连接委托
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        STRONG_SELF;
        if (![self isCurrentPage]) {
            return;
        }
        NSLog(@"====断开连接设备name：%@",peripheral.name);
        self->_isBegainConnect = NO;
        [self.baby cancelPeripheralConnection:peripheral];
        // ---断开链接后自动查找链接
        [self clearData];
        [self stopBluetooth];
        [self.waveLayer start];
        [self startSearch];
    }];
    
    // 查找到服务
    [self.baby setBlockOnDiscoverServices:^(CBPeripheral *peripheral, NSError *error) {
        for (CBService *service in peripheral.services) {
            NSLog(@"====查找到服务UUID：%@",service.UUID.UUIDString);
        }
    }];
               
    // 查找到特征值
    [self.baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        STRONG_SELF;
        if (![self isCurrentPage]) {
            return;
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];

        NSString *serviceUUID = [NSString stringWithFormat:@"%@",service.UUID];
        NSLog(@"====查找到服务UUID：%@",serviceUUID);
        if ([serviceUUID containsString:kServiceUUID] || [serviceUUID containsString:kWatch_ServiceUUID]) {

            for (CBCharacteristic *characteristic in service.characteristics) {
                
                NSString *characteristicUUID = [NSString stringWithFormat:@"%@",characteristic.UUID];
                 if([characteristicUUID containsString:kNotifyCharacteristicUUID] || [characteristicUUID containsString:kWatch_NotifyCharacteristicUUID]){
                     NSLog(@"====查找到notify characteristicUUID：%@",characteristicUUID);
                     ARTSingleShare.currentPeripheral = self.currentPeripheral;
                     self.currentCharacteristic = characteristic;
                     ARTSingleShare.currentCharacteristic = characteristic;
                     // 相关设备存储
                     [self storageDeviceWithPeripheral:peripheral];
                     
                     [[NSNotificationCenter defaultCenter] postNotificationName:ART_Notify_DeviceConnected object:@{@"peripheral":peripheral}];
                     [self destroyConnectTimer];
                     
                     [self destroySearchTimer];
                     
                     [self.baby cancelScan];
                     
                     if ([Tool deviceTypeWithName:self.currentPeripheral.name] == ARTDeviceTypeOximeter) {
                         if (!ARTSingleShare.hadLoadTabVC) {
                             [self gotoTabVCWithName:peripheral.name];
                         }else{
                             [[NSNotificationCenter defaultCenter] postNotificationName:APP_BECOME_TEST object:nil];
                         }
                     }else if ([Tool deviceTypeWithName:self.currentPeripheral.name] == ARTDeviceTypeWatch){
                         [self gotoWatchWithName:peripheral.name];
                     }
                 }else if ([characteristicUUID containsString:kWatch_WriteCharacteristicUUID]){
                     NSLog(@"====查找到write characteristicUUID：%@",characteristicUUID);
                     ARTSingleShare.writeCharacteristic = characteristic;
                     [self gotoWatchWithName:peripheral.name];
                 }
            }
        }
        
        // 接受到数据
        if ([Tool deviceTypeWithName:self.currentPeripheral.name] == ARTDeviceTypeFetalHeart || [Tool deviceTypeWithName:self.currentPeripheral.name] == ARTDeviceTypePlateau) {
            if (self.currentPeripheral && self.currentCharacteristic) {
                [self.baby notify:self.currentPeripheral characteristic:self.currentCharacteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
                    NSLog(@"收到数据%@",characteristics.value);
                    if (ARTSingleShare.hadLoadTabVC == NO) {
                        [self gotoTabVCWithName:peripheral.name];
                    }
                }];
            }
        }
    }];
}

- (BOOL)isCurrentPage{
    return [[ARTNavigation currentViewController] isKindOfClass:[self class]];
}

- (void)gotoWatchWithName:(NSString *)name{
    if (ARTSingleShare.writeCharacteristic && ARTSingleShare.currentCharacteristic) {
        if (ARTSingleShare.hadLoadTabVC == NO) {
            [self gotoTabVCWithName:name];
        }
    }
}

- (void)gotoTabVCWithName:(NSString *)name{
    ARTDeviceType type = [Tool deviceTypeWithName:name];
    if (type == ARTDeviceTypeUnknow) {
        return;
    }
    ARTMainTabController *vc = [[ARTMainTabController alloc] init];
    vc.monitorDevType = [Tool deviceTypeWithName:name];
    vc.selectedIndex = 0;
    [self.navigationController pushViewController:vc animated:YES];
    NSLog(@"===跳转手表实时");
}

#pragma mark--Notify TARGET ACTION
// 开启动画
- (void)startAnimation{
    [self.waveLayer start];
}

// 切换语言
- (void)refreshLanguage{
    self.title = FYLocalizedString(@"real_time", @"");
    [_historyBtn setTitle:FYLocalizedString(@"oxygen_quey_record", @"") forState:UIControlStateNormal];
    [_reSearchBtn setTitle:FYLocalizedString(@"blue_reset_scan", @"") forState:UIControlStateNormal];
    _searchStatusLabel.text = FYLocalizedString(@"bluetooth_device_scaning", @"");
    _noBluetoothLabel.text = FYLocalizedString(@"oxygen_open", @"");
    [_baseCollectionView reloadData];
}

- (void)disConnected{
    [self.dataArray removeAllObjects];
}

#pragma mark--BUTTON TARGET ACTION
- (void)histroyAction{
//    if ([NSUserDefaults jk_stringForKey:ART_Storage_DefaultDeviceUUID].length == 0) {
//        [self.view jk_makeToast:FYLocalizedString(@"blue_quey", @"")];
//        return;
//    }
    NSString *defaultDeviceUUID = [NSUserDefaults jk_stringForKey:ART_Storage_DefaultDeviceUUID];
    NSArray *dataArray = [NSUserDefaults jk_arrayForKey:ART_Storage_DeviceList];
    NSString *name = @"WS20";
    for (NSDictionary *dic in dataArray) {
        NSString *uuid = [dic valueForKey:@"mac"];
        if ([uuid isEqualToString:defaultDeviceUUID]) {
            name = [dic valueForKey:@"name"];
            break;
        }
    }
    
    ARTDeviceType type = [Tool deviceTypeWithName:name];
    ARTMainTabController *vc = [[ARTMainTabController alloc] init];
    vc.monitorDevType = type;
    vc.selectedIndex = 1;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)questionAction{
    HelpViewController *vc = [[HelpViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)reSearchAction{
    [self startSearch];
}

#pragma mark--TIMER TARGET ACTION
- (void)searchTimeAction{
    _searchTimeCount++;
    NSLog(@"#####当前搜索时间:%@",@(_searchTimeCount));

    if (_searchTimeCount >= 10) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self clearData];
        // 未能查找到设备
        [self noSearchDevice];
    }
}

- (void)connectTimeAction{
    _connectTimeCount++;
    NSLog(@"####当前连接时间:%@",@(_connectTimeCount));
    
    if (_connectTimeCount >= 10) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self clearData];
        
        [self destroyConnectTimer];
        
//        [self.view jk_makeToast:FYLocalizedString(@"oxygen_connecting_failed", @"")];
        [QMUITips showWithText:FYLocalizedString(@"oxygen_connecting_failed", @"")];
        
        [self stopBluetooth];
        [self startSearch];
    }
}

- (void)waitTimeAction{
    _waitTimeCount--;
    NSLog(@"####等待倒计时:%@",@(_waitTimeCount));

    [_reSearchBtn setTitle:[NSString stringWithFormat:@"%@ %@s",FYLocalizedString(@"blue_reset_scan", @""),@(_waitTimeCount)] forState:UIControlStateNormal];
//    self.reSearchLabel.text = [NSString stringWithFormat:@"%lds",(long)_waitTimeCount];
    if (_waitTimeCount <= 0) {
        _waitTimeCount = 0;
        [self startSearch];
    }
}

#pragma mark--PRIVATE METHOD
- (void)addWavePulsLayer {
    [self.view addSubview:self.bgView];
    [self.bgView.layer addSublayer:self.waveLayer];
    self.waveLayer.position = CGPointMake(XCScreenW/2, circleRadius);
}

// 开始工作
- (void)startSearch{
    [self destroyWaitTimer];
    
    self.reSearchLabel.hidden = self.reSearchBtn.hidden = self.searchImg.hidden = YES;
    self.waveLayer.hidden = self.searchStatusLabel.hidden = NO;
    self.promptLabel.text = FYLocalizedString(@"blue_careful_n", @"");
    
    [self initBluetooth];
}

// 停止工作
- (void)stopBluetooth{
    [self.baby cancelAllPeripheralsConnection];
    [self.baby cancelScan];
    self.baby = nil;
}

// 清空数据
- (void)clearData{
    self->_isBegainConnect = NO;
    self.dataArray = [NSMutableArray array];
    [self.baseCollectionView reloadData];
}

// 重置搜索timer
- (void)destroySearchTimer{
    [self.searchTimer invalidate];
    self.searchTimer = nil;
    _searchTimeCount = 0;
}

// 重置等待timer
- (void)destroyWaitTimer{
    [self.waitTimer invalidate];
    self.waitTimer = nil;
    _waitTimeCount = 5;
}

// 销毁连接timer
- (void)destroyConnectTimer{
    [self.connectTimer invalidate];
    self.connectTimer = nil;
    _connectTimeCount = 0;
}

// 没找到设备
- (void)noSearchDevice{
    [self.baby cancelScan];
    
    [self destroySearchTimer];
    
    self.reSearchBtn.hidden = self.searchImg.hidden = NO;
    self.waveLayer.hidden = self.searchStatusLabel.hidden = YES;
    self.promptLabel.text = FYLocalizedString(@"blue_careful_not", @"");
//    self.reSearchLabel.text = [NSString stringWithFormat:@"%lds",(long)_waitTimeCount];
    self.reSearchLabel.hidden = NO;
    
    _waitTimeCount = 5;
    self.waitTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(waitTimeAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.waitTimer forMode:NSRunLoopCommonModes];
}

// 存储设备列表
- (void)storageDeviceWithPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"--存储设备列表");
    NSString *mac = @"";
    if ([self.macAddressDictionary.allKeys containsObject:peripheral]) {
        mac = self.macAddressDictionary[peripheral];
    }
    NSMutableArray *array = [NSMutableArray arrayWithArray:[NSUserDefaults jk_arrayForKey:ART_Storage_DeviceList]];
    
    BOOL alreadyIn = NO;
    for (NSDictionary *dict in array) {
        if ([[dict valueForKey:@"mac"] isEqualToString:mac]) {
            alreadyIn = YES;
            break;
        }
    }
    if (!alreadyIn) {
        NSDictionary *dict = @{@"mac":mac,@"name":peripheral.name};
        [array addObject:dict];
        [NSUserDefaults jk_setObject:array forKey:ART_Storage_DeviceList];
    }
    if (array.count == 1) {
        [NSUserDefaults jk_setObject:mac forKey:ART_Storage_DefaultDeviceUUID];
    }
}

// 添加外设到数组
- (void)addDevice:(CBPeripheral *)peripheral advertisement:(NSDictionary *)advertisementData{
    NSLog(@"--添加外设到数组");
    BOOL alreadyIn = false;
    for (CBPeripheral *device2 in self.dataArray) {
        if ([peripheral.identifier.UUIDString isEqual:device2.identifier.UUIDString]) {
            alreadyIn = true;
            break;
        }
    }
    if (!alreadyIn && peripheral.name) {
        [self.dataArray addObject:peripheral];
        peripheral.delegate = self;
        // 保存Mac地址
        NSString *mac = [Tool macAddressWithAdvertisement:advertisementData];
        [self.macAddressDictionary setObject:mac forKey:peripheral];
        
        NSString *defaultMac = [NSUserDefaults jk_stringForKey:ART_Storage_DefaultDeviceUUID];
        if ([mac isEqualToString:defaultMac]) {
            // 如果为默认的设备，自动连接
            [self connectWithDevice:peripheral];
        }
    }
    [self.baseCollectionView reloadData];
}

// 连接设备
- (void)connectWithDevice:(CBPeripheral *)peripheral{
    if (![Tool isBloodWithName:peripheral.name] && ![Tool isFetalHeartWithName:peripheral.name] && ![Tool isWatchWithName:peripheral.name] && ![Tool isPelvicMusclesWithName:peripheral.name]) {
        return;
    }
    NSLog(@"连接设备");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _isBegainConnect = YES;
    // 开始连接设备
    self.currentPeripheral = peripheral;
    if (!self.baby) {
        self.baby = [BabyBluetooth shareBabyBluetooth];
        ARTSingleShare.baby = self.baby;
    }
    self.baby.having(peripheral).connectToPeripherals().discoverServices().discoverCharacteristics().readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
    
    if (!self.connectTimer) {
        _connectTimeCount = 0;
        self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(connectTimeAction) userInfo:nil repeats:YES];
        [self.connectTimer fire];
    }
    [[NSRunLoop currentRunLoop] addTimer:self.connectTimer forMode:NSRunLoopCommonModes];
    [self.baby cancelScan];
    [self destroyWaitTimer];
    
    [self destroySearchTimer];
    
    // 保存当前连接mac
    if ([self.macAddressDictionary.allKeys containsObject:peripheral]) {
        NSString *mac = self.macAddressDictionary[peripheral];
        [NSUserDefaults jk_setObject:mac forKey:ART_Storage_DefaultDeviceUUID];
    }
}

#pragma mark--UICollectionViewDelegate && UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

// 每个UICollectionView展示的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TopImageTwoBottomLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TopImageTwoBottomLabelCell" forIndexPath:indexPath];
    CBPeripheral *peripheral = self.dataArray[indexPath.item];
    cell.deviceType = [Tool deviceTypeWithName:peripheral.name];
    return cell;
}

// 定义每个Item 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = 110;
    CGFloat height = 124 + 30;
    return CGSizeMake(width, height);
}

// 定义每个UICollectionView中section 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0,10,0,10);
}

// 设置cell的列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

// 设置cell的行边距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    CBPeripheral *peripheral = [self.dataArray objectAtIndex:indexPath.row];
    [self connectWithDevice:peripheral];
}

#pragma mark--UIConfig
- (void)UIConfig{
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.historyBtn];
    [_historyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(260);
        make.height.mas_equalTo(40);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-30-BOTTOM_SAFE_HEIGHT);
    }];
    [self addWavePulsLayer];
    [self.view addSubview:self.searchStatusLabel];
    [_searchStatusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(85);
        make.centerX.equalTo(self.bgView);
        make.centerY.equalTo(self.bgView.mas_top).offset(circleRadius);
    }];
    [self.view addSubview:self.questionBtn];
    [_questionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(36);
        make.top.mas_equalTo(TOP_HEIGHT + 15);
        make.right.equalTo(self.view.mas_right).offset(-15);
    }];
    [self.view addSubview:self.promptLabel];
    [_promptLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.top.equalTo(self.searchStatusLabel.mas_bottom).offset(100);
        make.centerX.equalTo(self.view);
        
    }];
    [self.view addSubview:self.searchImg];
    [_searchImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.promptLabel.mas_top).offset(-30);
        make.height.mas_equalTo(200);
        make.width.mas_equalTo(260);
    }];
    [self.view addSubview:self.reSearchBtn];
    [_reSearchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.promptLabel.mas_bottom).offset(15);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(200);
    }];
    
    _reSearchLabel = [[UILabel alloc] init];
    _reSearchLabel.textColor = J_ColorFromHEX(0x0095B6);
    _reSearchLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.reSearchLabel];
    [_reSearchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.reSearchBtn.mas_right).offset(0);
        make.centerY.equalTo(self.reSearchBtn);
    }];
    [self resetCollectionView];

    [self.baseCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.top.equalTo(self.promptLabel.mas_bottom).offset(30);
        make.height.mas_equalTo(124 + 30);
    }];
    
    _noBluetoothLabel = [[UILabel alloc]init];
    _noBluetoothLabel.textColor = J_ColorFromHEX(0x666666);
    _noBluetoothLabel.font = J_Font(14);
    _noBluetoothLabel.text = FYLocalizedString(@"oxygen_open", @"");
    _noBluetoothLabel.numberOfLines = 0;
    _noBluetoothLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_noBluetoothLabel];
    [_noBluetoothLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_questionBtn.mas_top).offset(-10);
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).offset(14);
        make.right.equalTo(self.view).offset(-14);
    }];
}

- (void)resetCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.baseCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.baseCollectionView.delegate = self;
    self.baseCollectionView.dataSource = self;
    [self.baseCollectionView setBackgroundColor:[UIColor colorWithWhite:0.f alpha:0.f]];
    [self.baseCollectionView registerClass:[TopImageTwoBottomLabelCell class] forCellWithReuseIdentifier:@"TopImageTwoBottomLabelCell"];
    [self.baseCollectionView setShowsHorizontalScrollIndicator:NO];
    [self.view addSubview:self.baseCollectionView];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark--GETTER
- (UIImageView *)searchImg{
    if (!_searchImg) {
        _searchImg = [[UIImageView alloc] init];
        _searchImg.image = [UIImage imageNamed:@"default_search"];
    }
    return _searchImg;
}

- (UIButton *)reSearchBtn{
    if (!_reSearchBtn) {
        _reSearchBtn = [[UIButton alloc] init];
        [_reSearchBtn setTitle:FYLocalizedString(@"blue_reset_scan", @"") forState:UIControlStateNormal];
        [_reSearchBtn setTitleColor:J_ColorFromHEX(0x0095B6) forState:UIControlStateNormal];
        _reSearchBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_reSearchBtn addTarget:self action:@selector(reSearchAction) forControlEvents:UIControlEventTouchUpInside];
        _reSearchBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        _reSearchBtn.hidden = YES;
    }
    return _reSearchBtn;
}

- (UILabel *)promptLabel{
    if (!_promptLabel) {
        _promptLabel = [[UILabel alloc] init];
        _promptLabel.text = FYLocalizedString(@"blue_careful_n", @"");
        _promptLabel.numberOfLines = 0;
        _promptLabel.font = [UIFont systemFontOfSize:14];
        _promptLabel.textColor = J_ColorFromHEX(0x999999);
        _promptLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _promptLabel;
}

- (UIButton *)questionBtn{
    if (!_questionBtn) {
        _questionBtn = [[UIButton alloc] init];
        [_questionBtn addTarget:self action:@selector(questionAction) forControlEvents:UIControlEventTouchUpInside];
        [_questionBtn setBackgroundImage:[UIImage imageNamed:@"nav_ic_help"] forState:UIControlStateNormal];
//        [_questionBtn setImage:[UIImage imageNamed:@"nav_ic_help"] forState:UIControlStateNormal];
    }
    return _questionBtn;
}

- (UILabel *)searchStatusLabel{
    if (!_searchStatusLabel) {
        _searchStatusLabel = [[UILabel alloc] init];
        _searchStatusLabel.backgroundColor = J_ColorFromHEX(0x0095B6);
        _searchStatusLabel.font = [UIFont systemFontOfSize:16];
        _searchStatusLabel.textColor = [UIColor whiteColor];
        _searchStatusLabel.text = FYLocalizedString(@"bluetooth_device_scaning", @"");
        _searchStatusLabel.textAlignment = NSTextAlignmentCenter;
        _searchStatusLabel.layer.cornerRadius = 85/2;
        _searchStatusLabel.layer.masksToBounds = YES;
    }
    return _searchStatusLabel;;
}

- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        [_bgView setBackgroundColor:[UIColor whiteColor]];
        _bgView.frame = CGRectMake(0, TOP_HEIGHT, XCScreenW, circleRadius);
    }
    return _bgView;
}

- (XLKWavePulsLayer *)waveLayer {
    if (_waveLayer == nil) {
        _waveLayer = [XLKWavePulsLayer layer];
        _waveLayer.animationDuration = 8;
        _waveLayer.haloLayerNumber = 7;
        _waveLayer.fromValueForRadius = 0.15;
        _waveLayer.backgroundColor = J_ColorFromHEX(0x0095B6).CGColor;
        _waveLayer.radius = circleRadius;
    }
    return _waveLayer;
}

- (UIButton *)historyBtn{
    if (!_historyBtn) {
        _historyBtn = [[UIButton alloc] init];
        _historyBtn.layer.cornerRadius = 20.0f;
        _historyBtn.layer.borderWidth = 0.5;
        _historyBtn.layer.borderColor = J_ColorFromHEX(0x0095B6).CGColor;
        [_historyBtn setTitle:FYLocalizedString(@"oxygen_quey_record", @"") forState:UIControlStateNormal];
        [_historyBtn setTitleColor:J_ColorFromHEX(0x0095B6) forState:UIControlStateNormal];
        [_historyBtn addTarget:self action:@selector(histroyAction) forControlEvents:UIControlEventTouchUpInside];
        _historyBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _historyBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    }
    return _historyBtn;
}

- (NSMutableDictionary *)macAddressDictionary{
    if (!_macAddressDictionary) {
        _macAddressDictionary = [NSMutableDictionary dictionary];
    }
    return _macAddressDictionary;
}

@end
